package com.hunlian.makelove.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hunlian.makelove.R;
import com.hunlian.makelove.bean.SmsBean;
import com.hunlian.makelove.common.ContextUtils;
import com.hunlian.makelove.view.ClearEditText;

import java.util.ArrayList;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class SmsVerifyActivity extends BaseActivity{

	private SmsVerifyActivity mSelf;
	private Button mBtnGetVerifyCode,mBtnVerifyCode;
	private ClearEditText mEtPhone,mEtVerifyCode;
	// 填写从短信SDK应用后台注册得到的APPKEY 
	private static String APPKEY = "f85faa205440";
	// 填写从短信SDK应用后台注册得到的APPSECRET
	private static String APPSECRET = "fad9f751810e29b00154988328570bb6";
	private String mStrPhone;
	private String mFrom;
	private String mTitle;
	private ContextUtils cu = new ContextUtils();
	private final int SEND_VERIFY_CODE = 0;
	private EventHandler smsEventHandler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSelf = this;
		setContentView(R.layout.sms_verify);

		
		mStrPhone = getIntent().getStringExtra("phone");
		mFrom = getIntent().getStringExtra("from");
		if(mFrom.equals("register")){
			mTitle = "注册";
		}else if(mFrom.equals("forget")){
			mTitle = "找回密码";
		}
		
		ImageButton mIbBack = (ImageButton) findViewById(R.id.back);
		mIbBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mSelf.finish();
			}

		});		
		TextView mTvTitle = (TextView) findViewById(R.id.title);
		mTvTitle.setText(mTitle);
				
		mBtnGetVerifyCode = (Button) findViewById(R.id.btn_get_verify_code);
		mBtnVerifyCode = (Button) findViewById(R.id.btn_verify_code);
		mEtPhone = (ClearEditText) findViewById(R.id.et_phone);
		mEtVerifyCode = (ClearEditText) findViewById(R.id.et_verify_code);
		setListener();
		
		mEtPhone.setText(mStrPhone);

		mHandler.sendEmptyMessageDelayed(SEND_VERIFY_CODE,1500);

		//MobSDK.init(this, APPKEY, APPSECRET);
		// 如果希望在读取通信录的时候提示用户，可以添加下面的代码，并且必须在其他代码调用之前，否则不起作用；如果没这个需求，可以不加这行代码
		SMSSDK.setAskPermisionOnReadContact(true);

		// 创建EventHandler对象
		smsEventHandler = new EventHandler() {
			public void afterEvent(int event, int result, Object data) {

				// 处理你自己的逻辑
				Message msg = new Message();
				msg.arg1 = event;
				msg.arg2 = result;
				msg.obj = data;
				handler.sendMessage(msg);

			}
		};

		// 注册监听器
		SMSSDK.registerEventHandler(smsEventHandler);


		//弹出软键盘
		ArrayList<EditText> list = new ArrayList<EditText>();
		list.add(mEtPhone);
		list.add(mEtVerifyCode);
		cu.showInputKeyboard(list);
	}

	private void setListener() {
		mBtnGetVerifyCode.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {		
				boolean boo = checkPhoneNum(mEtPhone.getText().toString());
				if(boo){
					mStrPhone = mEtPhone.getText().toString();
					SMSSDK.getVerificationCode("86", mEtPhone.getText().toString());
					mBtnGetVerifyCode.setClickable(false);
					startTimeTread();
									
				}
			}
			
		});
		
		mBtnVerifyCode.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				boolean boo = checkPhoneNum(mEtPhone.getText().toString());
				if(boo==false){
					return;
				}
				if(!TextUtils.isEmpty(mEtVerifyCode.getText().toString())){
					SMSSDK.submitVerificationCode("86", mStrPhone, mEtVerifyCode.getText().toString());
				}else {
					Toast.makeText(mSelf, "验证码不能为空", Toast.LENGTH_LONG).show();
				}
				
			}
			
		});
	}
	
	/** 检查电话号码 */
	private boolean checkPhoneNum(String phone) {

		if (TextUtils.isEmpty(phone)) {
			int resId = getStringRes(mSelf, "smssdk_write_mobile_phone");
			if (resId > 0) {
				Toast.makeText(mSelf, resId, Toast.LENGTH_SHORT).show();
			}
			return false;
		}


		if(phone.length() != 11) {
			int resId = getStringRes(mSelf, "smssdk_write_right_mobile_phone");
			if (resId > 0) {
				Toast.makeText(mSelf, resId, Toast.LENGTH_SHORT).show();
			}
			return false;
		}

		//通过检查
		return true;
	}
	

	public static int getStringRes(Context paramContext, String paramString) { 
        return paramContext.getResources().getIdentifier(paramString, "string", 
                paramContext.getPackageName()); 
    } 
	
	
	Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int event = msg.arg1;
			int result = msg.arg2;
			Object data = msg.obj;
			Log.e("event", "event="+event);

			if (result == SMSSDK.RESULT_COMPLETE) {
				//回调完成
				if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
					//提交验证码成功
					Toast.makeText(getApplicationContext(), "验证成功", Toast.LENGTH_SHORT).show();
					//跳转到输入密码页面
					Intent intent = new Intent(mSelf,RegisterActivity.class);
					intent.putExtra("phone", mStrPhone);
					intent.putExtra("from", mFrom);
					startActivity(intent);
					mSelf.finish();
				}else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
					//获取验证码成功
					Toast.makeText(getApplicationContext(), "短信已经发送", Toast.LENGTH_SHORT).show();
				}else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){
					//返回支持发送验证码的国家列表
				}
			}else {
				((Throwable) data).printStackTrace();

				SmsBean smsBean = new Gson().fromJson(((Throwable) data).getMessage(), SmsBean.class);
				if(smsBean==null)return;
				Toast.makeText(mSelf, smsBean.getDetail(), Toast.LENGTH_SHORT).show();
			}
		}
		
	};
	
	Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				mBtnGetVerifyCode.setText("" + msg.arg1 + "秒后重新获取");
				break;
			case 2:
				mBtnGetVerifyCode.setText("	获取验证码 	");
				mBtnGetVerifyCode.setClickable(true);
				break;
			default:
				break;
			}
		}
	};

	private void startTimeTread() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				for (int i = 90; i > 0; i--) {
					try {
						Thread.sleep(1000);
						Message msg = new Message();
						msg.what = 1;
						msg.arg1 = i;
						mhandler.sendMessage(msg);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
				mhandler.sendEmptyMessage(2);
			}
		}.start();
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			mBtnGetVerifyCode.performClick();
		};
	};
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		SMSSDK.unregisterEventHandler(smsEventHandler);
		SMSSDK.unregisterAllEventHandler();
	}


}